package cn.itrip.auth.controller;

import cn.itrip.auth.exception.TokenDateException;
import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.ErrorCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

/**
 * @author Tequila
 **/
@CrossOrigin
@RestController
@RequestMapping("/auth/api")
public class TokenController {

    @Autowired
    private TokenService tokenService;


    @PostMapping("/retoken")
    public Dto reToken(HttpServletRequest request){

            String token = request.getHeader("token");
            String userAgent = request.getHeader("user-agent");
            if (EmptyUtils.isNotEmpty(token)){
                try {
                    ItripTokenVO tokenVO = tokenService.reToken(token,userAgent);
                    return DtoUtil.returnDataSuccess(tokenVO);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return DtoUtil.returnFail("时间解析异常",ErrorCode.DATE_ERROR);
                } catch (TokenDateException e) {
                    e.printStackTrace();
                    return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_TOKEN_INVALID);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    return DtoUtil.returnFail("json转换异常",ErrorCode.JSON_ERROR);
                }

            }else{
                return DtoUtil.returnFail("token不能为空", ErrorCode.PARAM_ISNULL);
            }



    }

}
